// 员工考勤内容组件
Vue.component('employee-attendance-content', {
  data() {
    return {
      attendanceDays: 0,
      lateCount: 0,
      absentCount: 0,
      earlyLeaveCount: 0,
      records: [],
      totalRecords: 0,
      currentPage: 1,
      pageSize: 10,
      selectedDate: (() => {
        const now = new Date();
        return `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`;
      })(),
      // 今日打卡状态
      todayStatus: {
        hasCheckedIn: false,
        hasCheckedOut: false,
        checkInTime: null,
        checkOutTime: null
      },
      // 按钮加载状态
      checkInLoading: false,
      checkOutLoading: false
    };
  },
  mounted() {
    // 组件挂载后获取考勤数据
    this.fetchAttendanceData();
    // 获取今日打卡状态
    this.fetchTodayStatus();
  },
  template: `
    <div style="padding: 32px; width: 100%; box-sizing: border-box;">
      <el-card shadow="hover" style="width: 100%;">
        <!-- 顶部筛选区 -->
        <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 16px; margin-bottom: 24px;">
          <div style="display: flex; align-items: center; gap: 16px;">
            <span style="font-size: 22px; font-weight: bold;">{{ selectedDate ? selectedDate.replace('-', '年') + '月' : '请选择年月' }}考勤统计</span>
            <el-date-picker v-model="selectedDate" type="month" placeholder="选择年月" style="width: 150px;" value-format="yyyy-MM" @change="handleFilter" :clearable="false"></el-date-picker>
          </div>
          <div style="display: flex; align-items: center; gap: 8px;">
            <el-button 
              type="primary" 
              :loading="checkInLoading"
              :disabled="todayStatus.hasCheckedIn"
              @click="handleCheckIn"
              size="medium">
              {{ todayStatus.hasCheckedIn ? '已签到' : '签到' }}
            </el-button>
            <el-button 
              type="success" 
              :loading="checkOutLoading"
              :disabled="todayStatus.hasCheckedOut || !todayStatus.hasCheckedIn"
              @click="handleCheckOut"
              size="medium">
              {{ todayStatus.hasCheckedOut ? '已签退' : '签退' }}
            </el-button>
          </div>
        </div>
        <!-- 统计区 -->
        <div style="background: #f7f8fa; border-radius: 8px; padding: 18px 0 12px 0; margin-bottom: 28px;">
          <el-row :gutter="32" justify="center">
            <el-col :span="6">
              <el-statistic title="出勤天数" :value="attendanceDays" suffix="天"></el-statistic>
            </el-col>
            <el-col :span="6">
              <el-statistic title="迟到次数" :value="lateCount" suffix="次"></el-statistic>
            </el-col>
            <el-col :span="6">
              <el-statistic title="缺勤次数" :value="absentCount" suffix="次"></el-statistic>
            </el-col>
            <el-col :span="6">
              <el-statistic title="早退次数" :value="earlyLeaveCount" suffix="次"></el-statistic>
            </el-col>
          </el-row>
        </div>
        <!-- 表格区 -->
        <el-table :data="records" style="width: 100%; margin-bottom: 18px;">
          <el-table-column prop="date" label="日期" width="120"></el-table-column>
          <el-table-column prop="status" label="状态" width="100"></el-table-column>
          <el-table-column prop="checkIn" label="签到时间" width="120"></el-table-column>
          <el-table-column prop="checkOut" label="签退时间" width="120"></el-table-column>
        </el-table>
        <!-- 分页区 -->
        <div style="margin: 12px 0 0; text-align: right;">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="totalRecords"
            :page-size="pageSize"
            :current-page.sync="currentPage"
            @current-change="handlePageChange"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  `,
  methods: {
    // 获取考勤数据
    fetchAttendanceData() {
      const params = {
        page: this.currentPage,
        per_page: this.pageSize
      };
      
      // 如果选择了年月，添加日期范围筛选
      if (this.selectedDate) {
        // 解析年月
        const [year, month] = this.selectedDate.split('-').map(Number);
        // 设置开始日期为当月第一天
        const startDate = `${year}-${month.toString().padStart(2, '0')}-01`;
        // 设置结束日期为当月最后一天
        const lastDay = new Date(year, month, 0).getDate();
        const endDate = `${year}-${month.toString().padStart(2, '0')}-${lastDay}`;
        
        params.start_date = startDate;
        params.end_date = endDate;
      }
      
      attendanceAPI.getAttendances(params)
        .then(response => {
            // 转换API返回的数据为组件需要的格式
            // 根据API实际返回结构，数据在data字段中（data和attendances都肯定存在，即使为空数组）
            const data = response.data;
            this.records = data.attendances.map(item => {
              let checkIn = '-';
              let checkOut = '-';
              let status = '正常';
              
              // 格式化签到时间
              if (item.check_in_time) {
                const checkInTime = new Date(item.check_in_time);
                checkIn = `${checkInTime.getHours().toString().padStart(2, '0')}:${checkInTime.getMinutes().toString().padStart(2, '0')}`;
              }
              
              // 格式化签退时间
              if (item.check_out_time) {
                const checkOutTime = new Date(item.check_out_time);
                checkOut = `${checkOutTime.getHours().toString().padStart(2, '0')}:${checkOutTime.getMinutes().toString().padStart(2, '0')}`;
              }
              
              // 使用后端返回的状态
              if (item.status) {
                switch (item.status) {
                  case 'present':
                    status = '正常';
                    break;
                  case 'late':
                    status = '迟到';
                    break;
                  case 'absent':
                    status = '缺勤';
                    break;
                  case 'early_leave':
                    status = '早退';
                    break;
                  default:
                    status = '正常';
                }
              }
              
              return {
                date: item.date,
                status: status,
                checkIn: checkIn,
                checkOut: checkOut
              };
            });
            
            // 更新分页信息 - 从pagination字段获取
            this.totalRecords = data.pagination?.total || 0;  // 从pagination中获取total
            this.currentPage = data.pagination?.page || 1;    // 从pagination中获取page
            
            // 计算考勤统计
            this.calculateAttendanceStats();
            // 更新今日打卡状态
            this.fetchTodayStatus();
        })
        .catch(error => {
          console.error('获取考勤数据错误:', error);
          this.$message.error(error.message || '获取考勤数据失败');
        });
    },
    
    // 计算考勤统计数据
    calculateAttendanceStats() {
      let attendanceDays = 0;
      let lateCount = 0;
      let absentCount = 0;
      let earlyLeaveCount = 0;
      
      this.records.forEach(record => {
        if (record.status === '正常' && record.checkIn !== '-') {
          attendanceDays++;
        } else if (record.status === '迟到') {
          attendanceDays++;
          lateCount++;
        } else if (record.status === '缺勤') {
          absentCount++;
        } else if (record.status === '早退') {
          attendanceDays++;
          earlyLeaveCount++;
        }
      });
      
      this.attendanceDays = attendanceDays;
      this.lateCount = lateCount;
      this.absentCount = absentCount;
      this.earlyLeaveCount = earlyLeaveCount;
    },
        
    // 分页变化处理
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchAttendanceData();
    },
    
    // 筛选变化处理
    handleFilter() {
      this.currentPage = 1;
      this.fetchAttendanceData();
    },
    
    // 获取今日打卡状态
    fetchTodayStatus() {
      const today = new Date().toISOString().split('T')[0]; // 获取今天的日期 YYYY-MM-DD
      
      // 查找今天的考勤记录
      const todayRecord = this.records.find(record => record.date === today);
      
      if (todayRecord) {
        this.todayStatus.hasCheckedIn = todayRecord.checkIn !== '-';
        this.todayStatus.hasCheckedOut = todayRecord.checkOut !== '-';
        this.todayStatus.checkInTime = todayRecord.checkIn !== '-' ? todayRecord.checkIn : null;
        this.todayStatus.checkOutTime = todayRecord.checkOut !== '-' ? todayRecord.checkOut : null;
      } else {
        // 重置状态
        this.todayStatus.hasCheckedIn = false;
        this.todayStatus.hasCheckedOut = false;
        this.todayStatus.checkInTime = null;
        this.todayStatus.checkOutTime = null;
      }
    },
    
    // 处理签到
    async handleCheckIn() {
      this.checkInLoading = true;
      try {
        await attendanceAPI.checkIn();
        this.$message.success('签到成功！');
        // 重新获取考勤数据以更新状态
        await this.fetchAttendanceData();
        this.fetchTodayStatus();
      } catch (error) {
        console.error('签到失败:', error);
        this.$message.error(error.message || '签到失败，请重试');
      } finally {
        this.checkInLoading = false;
      }
    },
    
    // 处理签退
    async handleCheckOut() {
      this.checkOutLoading = true;
      try {
        await attendanceAPI.checkOut();
        this.$message.success('签退成功！');
        // 重新获取考勤数据以更新状态
        await this.fetchAttendanceData();
        this.fetchTodayStatus();
      } catch (error) {
        console.error('签退失败:', error);
        this.$message.error(error.message || '签退失败，请重试');
      } finally {
        this.checkOutLoading = false;
      }
    }
  }
});
